package org.springblade.modules.repair.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.common.cache.DictCache;
import org.springblade.common.config.ProjectApiConfiguration;
import org.springblade.common.enums.FeiShuDocumentEnum;
import org.springblade.common.utils.AsyncHttpUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.flow.business.service.FlowBusinessService;
import org.springblade.flow.core.constant.ProcessConstant;
import org.springblade.flow.core.entity.BladeFlow;
import org.springblade.flow.repair.parts.enums.PartsApproveRoleEnum;
import org.springblade.flow.repair.parts.service.IPartsService;
import org.springblade.flow.repair.parts.vo.ProcessTaskVO;
import org.springblade.modules.repair.dto.PartsWorkSaveDTO;
import org.springblade.modules.repair.dto.UpdateBitableDataDTO;
import org.springblade.modules.repair.entity.*;
import org.springblade.modules.repair.enums.MaintainPlanContentEnum;
import org.springblade.modules.repair.enums.PlanContentFormTypeEnum;
import org.springblade.modules.repair.service.IMaintainPlanContentService;
import org.springblade.modules.repair.enums.*;
import org.springblade.modules.repair.service.*;
import org.springblade.modules.repair.service.approve.strategy.ApproveBusinessFlow;
import org.springblade.modules.repair.service.approve.strategy.ApproveBusinessStrategy;
import org.springblade.modules.repair.vo.*;
import org.springblade.modules.repair.vo.PartsSimpleInfoVO;
import org.springblade.modules.repair.vo.flow.ApproveVo;
import org.springblade.modules.repair.vo.part.PartWordUrlVo;
import org.springblade.modules.system.entity.Region;
import org.springblade.modules.system.service.IRegionService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springblade.modules.repair.mapper.MaintainPartsWorkMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MaintainPartsWorkServiceImpl extends BaseServiceImpl<MaintainPartsWorkMapper, MaintainPartsWork> implements MaintainPartsWorkService {

	@Autowired
	private IMaintainPlanContentService planContentService;

	@Autowired
	private IMaintainPlanContentUserService planContentUserService;
	@Autowired
	private IMaintainPlanRelationService planRelationService;
	@Autowired
	private IMaintainMalfunctionHistoryService malfunctionHistoryService;
	@Autowired
	private IMaintainMalfunctionLogService malfunctionLogService;
	@Autowired
	private IMaintainSignService signService;
	@Lazy
	@Autowired
	private IUserService userService;
	@Autowired
	@Lazy
	private IPartsService partsService;
	@Autowired
	private FlowBusinessService flowBusinessService;
	@Autowired
	private IMaintainPlanContentExtService planContentExtService;
	@Autowired
	private IPartAddressService partAddressService;
	@Autowired
	private IRegionService regionService;
	@Autowired
	@Lazy
	private MaintainPartsWorkService maintainPartsWorkService;
	@Autowired
	private AsyncHttpUtil asyncHttpUtil;
	@Autowired
	private ProjectApiConfiguration projectApiConfiguration;
	@Autowired
	private BusinessApproveService businessApproveService;
	@Autowired
	private Environment environment;

	@Autowired
	private IElevatorAttachmentHistoryService elevatorAttachmentHistoryService;
	@Autowired
	private MaintainPartsWorkSkuService partsWorkSkuService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean savePartsWork(PartsWorkSaveDTO partsWorkSaveDTO) {
		List<Long> elevatorIds = partsWorkSaveDTO.getElevatorIds();
		for (Long currentElevatorId : elevatorIds) {
			// 更新工单主表记录
			MaintainPlanContent planContent = new MaintainPlanContent();
			planContent.setElevatorId(currentElevatorId);
			planContent.setTypeStatus(MaintainPlanContentEnum.MAINTAIN_PARTS.getId());
			planContent.setPlanDate(DateUtil.date());
			planContent.setPlanFrom(PlanContentFormTypeEnum.REPAIR.getId());
			planContent.setStatus(TaskStatusEnum.PARTS_APPLY.getStatus());
			planContentService.save(planContent);

			List<MaintainPartsWorkSku> skuList = new ArrayList<>();
			for (int t = 0; t < partsWorkSaveDTO.getPartsList().size(); t++) {
				PartsWorkSaveDTO.PartsList partsList = partsWorkSaveDTO.getPartsList().get(t);
				// 更新工单副表详情记录
				MaintainPartsWork partsWork = new MaintainPartsWork();
				BeanUtil.copyProperties(partsList, partsWork);
				BeanUtil.copyProperties(partsWorkSaveDTO, partsWork);
				partsWork.setPlanId(planContent.getId());
				partsWork.setFinallySkuId(partsList.getSkuId());
				if (Func.isNotEmpty(partsList.getSkuPartsInfo())) {
					partsWork.setFinallySkuPartsInfo(new JSONObject(partsList.getSkuPartsInfo()));
				}
				super.save(partsWork);

				if(Func.isNotEmpty(partsList.getSkuList())){
					partsList.getSkuList().forEach(e -> {
						e.setWorkId(partsWork.getId());
					});
					skuList.addAll(partsList.getSkuList());
				}
			}
			if(Func.isNotEmpty(skuList)){
				partsWorkSkuService.saveBatch(skuList);
			}

			// 更新工单关联表记录
			if (!Func.isNull(partsWorkSaveDTO.getFromPlanId())) {
				MaintainPlanRelation planRelation = new MaintainPlanRelation();
				planRelation.setOwnPlanId(planContent.getId());
				planRelation.setFromPlanId(partsWorkSaveDTO.getFromPlanId());
				planRelationService.save(planRelation);
			}

			// 初始化工单扩展表
			MaintainPlanContentExt maintainPlanContentExt = new MaintainPlanContentExt();
			maintainPlanContentExt.setPlanId(planContent.getId());
			maintainPlanContentExt.setElevatorStop(partsWorkSaveDTO.getElevatorStop());
			maintainPlanContentExt.setEmerProcType(partsWorkSaveDTO.getEmerProcType());
			maintainPlanContentExt.setWorkOrderType(partsWorkSaveDTO.getWorkOrderType());
			maintainPlanContentExt.setElevatorNameAttachment(JSON.toJSONString(partsWorkSaveDTO.getNameAttachment()));
			planContentExtService.save(maintainPlanContentExt);

			// 插入任务追踪记录
			malfunctionLogService.insertWorkLog(planContent.getId(), WorkTrackStatusEnum.PARTS_WORK.getTypeName(), TaskStatusEnum.PARTS_APPLY.getStatus());

			//2023-09-20新增配件收货地址
			if (partsWorkSaveDTO.getPartAddress() != null) {
				PartAddress partAddress = partsWorkSaveDTO.getPartAddress();
				partAddress.setId(null);
				partAddress.setPlanId(planContent.getId());
				List<Region> regions = regionService.list(Wrappers.<Region>lambdaQuery().eq(Region::getDistrictCode, partAddress.getAdCode()));
				if (!regions.isEmpty()) {
					partAddress.setProvinceName(regions.get(0).getProvinceName());
					partAddress.setCityName(regions.get(0).getCityName());
					partAddress.setAdName(regions.get(0).getDistrictName());
				}
				partAddressService.save(partAddress);
			}

			// 创建审批流程
			ApproveBusinessFlow approveFlow = ApproveBusinessStrategy.get(ApproveTypeEnum.ACCESSORY_APPLY.getId());
			BusinessApproveVO businessApprove = new BusinessApproveVO();
			businessApprove.setName(ApproveTypeEnum.ACCESSORY_APPLY.getName());
			businessApprove.setType(ApproveTypeEnum.ACCESSORY_APPLY.getId());
			businessApprove.setSubmitId(AuthUtil.getUserId());
			businessApprove.setSubmitName(AuthUtil.getNickName());
			businessApprove.setWorkOrderId(planContent.getId());
			businessApprove.setApproveStatus(ApproveStatusEnum.PENDING.getId());
			approveFlow.addApprove(businessApprove);

			//新增电梯铭牌 2025-06 修改为先查看当前电梯是否已有电梯铭牌
			List<ElevatorAttachmentHistory> attachmentExitstList = elevatorAttachmentHistoryService.list(new LambdaUpdateWrapper<ElevatorAttachmentHistory>()
				.eq(ElevatorAttachmentHistory::getElevatorId, currentElevatorId)
				.eq(BaseEntity::getStatus, ElevatorAttachmentEnum.NAME.getStatus())
				.eq(BaseEntity::getIsDeleted, 0)
			);
			if (Func.isEmpty(attachmentExitstList) && Func.isNotEmpty(partsWorkSaveDTO.getNameAttachment())) {
				ElevatorAttachmentHistory elevatorAttachmentHistory = new ElevatorAttachmentHistory();
				elevatorAttachmentHistory.setElevatorId(currentElevatorId);
				elevatorAttachmentHistory.setStatus(ElevatorAttachmentEnum.NAME.getStatus());
				// 2025-06 电梯铭牌在审核后再真正插入到elevator_attachment_history表中
//			elevatorAttachmentHistory.setAttachment(JSON.toJSONString(partsWorkSaveDTO.getNameAttachment()));
//			elevatorAttachmentHistoryService.save(elevatorAttachmentHistory);
			}
		}
		return true;
	}

	@Deprecated
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updatePartsWorkStatus(ProcessTaskVO processPass) {
		MaintainPlanContent planContent = planContentService.getOne(Wrappers.<MaintainPlanContent>lambdaQuery().eq(MaintainPlanContent::getProcessInstanceId, processPass.getProcessInstanceId()));
		if (ObjectUtil.isEmpty(planContent)) {
			throw new ServiceException("未查到指定工单");
		}
		Integer planStatus = Integer.valueOf(processPass.getStatus());
		planContent.setStatus(planStatus);
		planContentService.updateById(planContent);
		//如果是关闭状态,更新报价记录为审核不通过状态
		if (planStatus == TaskStatusEnum.PARTS_CLOSE.getStatus()) {
			MaintainPartsWork one = maintainPartsWorkService.getOne(Wrappers.<MaintainPartsWork>lambdaQuery().eq(MaintainPartsWork::getPlanId, planContent.getId()));
			one.setStatus(StatusEnum.DISABLE.getId());
			maintainPartsWorkService.updateById(one);
		}

		ApproveVo approveVo = new ApproveVo();
		approveVo.setComment(processPass.getComment());

		// 插入部件更换记录
		malfunctionLogService.insertWorkLog(planContent.getId(), TaskStatusEnum.getTaskName(MaintainPlanContentEnum.MAINTAIN_PARTS.getId(), planStatus), planStatus, JSON.toJSONString(approveVo), processPass.getAssignee(), processPass.getAssigneeName());
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Boolean editPartsWork(PartsWorkSaveDTO partsWorkSaveDTO) {
		MaintainPlanContent maintainPlanContent = planContentService.getById(partsWorkSaveDTO.getPlanId());
		if (maintainPlanContent == null) {
			throw new ServiceException("工单不存在!");
		}
		BusinessApprove businessApprove = businessApproveService.getByWorkOrderId(partsWorkSaveDTO.getPlanId());
		if (businessApprove == null) {
			throw new ServiceException("审批流程不存在!");
		}
		if (!Func.equalsSafe(AuthUtil.getUserId(), businessApprove.getSubmitId())) {
			throw new ServiceException("您不是申请人，不能重新提交申请");
		}

		boolean checkEdit = businessApprove.getApproveStatus() == ApproveStatusEnum.PENDING.getId() && maintainPlanContent.getStatus() == TaskStatusEnum.PARTS_APPLY.getStatus();
		if (!checkEdit) {
			throw new ServiceException("该工单已审批，不能编辑");
		}

		// 更新工单副表详情记录
		List<PartsWorkSaveDTO.PartsList> partsList = partsWorkSaveDTO.getPartsList();
		List<Long> partsWorkIds = partsWorkSaveDTO.getPartsList().stream().filter(e -> Func.isNotEmpty(e.getId())).map(PartsWorkSaveDTO.PartsList::getId).collect(Collectors.toList());
		super.remove(Wrappers.<MaintainPartsWork>lambdaQuery().eq(MaintainPartsWork::getPlanId,maintainPlanContent.getId()).notIn(MaintainPartsWork::getId,partsWorkIds));
		List<MaintainPartsWork> resultPartsWorkList = new ArrayList<>();
		List<MaintainPartsWorkSku> skuList = new ArrayList<>();
		partsList.forEach(e -> {
			MaintainPartsWork partsWork = new MaintainPartsWork();
			BeanUtil.copyProperties(e, partsWork);
			resultPartsWorkList.add(partsWork);

			if(Func.isNotEmpty(e.getSkuList())){
				e.getSkuList().forEach(t -> {
					t.setWorkId(e.getId());
				});
				skuList.addAll(e.getSkuList());
			}
		});
		super.saveOrUpdateBatch(resultPartsWorkList);

		List<Long> partsSkuIds = skuList.stream().map(MaintainPartsWorkSku::getId).collect(Collectors.toList());
		List<Long> workId = resultPartsWorkList.stream().map(MaintainPartsWork::getId).collect(Collectors.toList());
		if(Func.isNotEmpty(partsSkuIds)){
			partsWorkSkuService.remove(Wrappers.<MaintainPartsWorkSku>lambdaQuery().in(MaintainPartsWorkSku::getWorkId,workId).notIn(MaintainPartsWorkSku::getId,partsSkuIds));
		}else {
			partsWorkSkuService.remove(Wrappers.<MaintainPartsWorkSku>lambdaQuery().in(MaintainPartsWorkSku::getWorkId,workId));
		}
		if(Func.isNotEmpty(skuList)){
			partsWorkSkuService.saveOrUpdateBatch(skuList);
		}

		// 更新地址
		if (partsWorkSaveDTO.getPartAddress() != null) {
			PartAddress partAddress1 = partsWorkSaveDTO.getPartAddress();
			List<PartAddress> list = partAddressService.list(Wrappers.<PartAddress>lambdaQuery().eq(PartAddress::getPlanId, partsWorkSaveDTO.getPlanId()));
			partAddress1.setId(list.get(0).getId());
			partAddressService.updateById(partAddress1);
		}

		// 更新工单ext表
		planContentExtService.update(Wrappers.<MaintainPlanContentExt>lambdaUpdate()
			.set(MaintainPlanContentExt::getEmerProcType, partsWorkSaveDTO.getEmerProcType())
				.set(MaintainPlanContentExt::getElevatorNameAttachment,JSON.toJSONString(partsWorkSaveDTO.getNameAttachment()))
			.eq(MaintainPlanContentExt::getPlanId, partsWorkSaveDTO.getPlanId()));

		return true;
	}

	@Transactional(rollbackFor = Exception.class)
	@Override
	public Boolean resubmitPartsWork(PartsWorkSaveDTO partsWorkSaveDTO) {
		// 2025-06 新增电梯铭牌
		Long planId = partsWorkSaveDTO.getPlanId();
		if(Func.isEmpty(planId)){
			throw new ServiceException("传参工单信息有误，工单不存在!");
		}
		BusinessApprove businessApprove = businessApproveService.getByWorkOrderId(planId);
		if (businessApprove == null) {
			throw new ServiceException("审批流程不存在!");
		}
		if (businessApprove.getApproveStatus() != ApproveStatusEnum.RETURN.getId()) {
			throw new ServiceException("该申请未退回，不能重新提交!");
		}
		if (!Func.equalsSafe(AuthUtil.getUserId(), businessApprove.getSubmitId())) {
			throw new ServiceException("您不是申请人，不能重新提交申请");
		}

		MaintainPlanContent planContent = planContentService.getById(planId);

		if (planContent == null) {
			throw new ServiceException("工单不存在!");
		}
		planContent.setStatus(TaskStatusEnum.PARTS_APPLY.getStatus());
		boolean planContentFlag = planContentService.updateById(planContent);

		// 防止测试库有极端测试数据，使用list
		List<MaintainPlanContentExt> planContentExtList = planContentExtService.list(
			Wrappers.<MaintainPlanContentExt>lambdaQuery()
				.eq(BaseEntity::getIsDeleted, 0)
				.eq(MaintainPlanContentExt::getPlanId, planId)
				.orderByDesc(BaseEntity::getCreateTime)
		);
		if(Func.isEmpty(planContentExtList)){
			throw new ServiceException("初次提交后该工单信息不完整工单扩展信息不存在!");
		}
		// 2025-06 当已有电梯铭牌，不做处理；当未有电梯铭牌，更新电梯铭牌到maintain_plan_content_ext表中暂存
		MaintainPlanContentExt maintainPlanContentExt = planContentExtList.get(0);
		maintainPlanContentExt.setElevatorNameAttachment(JSON.toJSONString(partsWorkSaveDTO.getNameAttachment()));
		planContentExtService.updateById(maintainPlanContentExt);

		// 更新工单副表详情记录
		List<PartsWorkSaveDTO.PartsList> partsList = partsWorkSaveDTO.getPartsList();
		List<Long> partsWorkIds = partsWorkSaveDTO.getPartsList().stream().filter(e -> Func.isNotEmpty(e.getId())).map(PartsWorkSaveDTO.PartsList::getId).collect(Collectors.toList());
		super.remove(Wrappers.<MaintainPartsWork>lambdaQuery().eq(MaintainPartsWork::getPlanId,planContent.getId()).notIn(MaintainPartsWork::getId,partsWorkIds));
		List<MaintainPartsWork> resultPartsWorkList = new ArrayList<>();
		List<MaintainPartsWorkSku> skuList = new ArrayList<>();
		partsList.forEach(e -> {
			MaintainPartsWork partsWork = new MaintainPartsWork();
			BeanUtil.copyProperties(e, partsWork);
			resultPartsWorkList.add(partsWork);

			if(Func.isNotEmpty(e.getSkuList())){
				e.getSkuList().forEach(t -> {
					t.setWorkId(e.getId());
				});
				skuList.addAll(e.getSkuList());
			}
		});
		boolean planRes = super.saveOrUpdateBatch(resultPartsWorkList);
		List<Long> partsSkuIds = skuList.stream().map(MaintainPartsWorkSku::getId).collect(Collectors.toList());
		List<Long> workId = resultPartsWorkList.stream().map(MaintainPartsWork::getId).collect(Collectors.toList());
		if(Func.isNotEmpty(partsSkuIds)){
			partsWorkSkuService.remove(Wrappers.<MaintainPartsWorkSku>lambdaQuery().in(MaintainPartsWorkSku::getWorkId,workId).notIn(MaintainPartsWorkSku::getId,partsSkuIds));
		}else {
			partsWorkSkuService.remove(Wrappers.<MaintainPartsWorkSku>lambdaQuery().in(MaintainPartsWorkSku::getWorkId,workId));
		}
		if(Func.isNotEmpty(skuList)){
			partsWorkSkuService.saveOrUpdateBatch(skuList);
		}

		// 更新地址
		if (partsWorkSaveDTO.getPartAddress() != null) {
			PartAddress partAddress1 = partsWorkSaveDTO.getPartAddress();
			List<PartAddress> list = partAddressService.list(Wrappers.<PartAddress>lambdaQuery().eq(PartAddress::getPlanId, partsWorkSaveDTO.getPlanId()));
			partAddress1.setId(list.get(0).getId());
			partAddressService.updateById(partAddress1);
		}

		// 更新工单ext表
		planContentExtService.update(Wrappers.<MaintainPlanContentExt>lambdaUpdate()
			.set(MaintainPlanContentExt::getEmerProcType, partsWorkSaveDTO.getEmerProcType())
			.eq(MaintainPlanContentExt::getPlanId, partsWorkSaveDTO.getPlanId()));

		// 插入任务追踪记录
		malfunctionLogService.insertWorkLog(partsWorkSaveDTO.getPlanId(), "重新" + WorkTrackStatusEnum.PARTS_WORK.getTypeName(), TaskStatusEnum.PARTS_APPLY.getStatus());

		// 更新审批
		BusinessApproveVO businessApproveVO = new BusinessApproveVO();
		businessApproveVO.setId(businessApprove.getId());
		businessApproveVO.setWorkOrderId(businessApprove.getWorkOrderId());
		businessApproveVO.setApproveStatus(ApproveStatusEnum.PENDING.getId());
		businessApproveVO.setRemark(null);
		ApproveBusinessFlow flowStrategy = ApproveBusinessStrategy.get(ApproveTypeEnum.ACCESSORY_APPLY.getId());
		boolean flowRes = flowStrategy.addApprove(businessApproveVO);

		if (!planContentFlag || !planRes || !flowRes) {
			throw new ServiceException("工单重新提交失败，工单id: " + partsWorkSaveDTO.getPlanId());
		}

		return true;
	}

	@Override
	public Boolean finish(MaintainPlanContent partsWorkSaveDTO) {
		MaintainPlanContent planContent = planContentService.getById(partsWorkSaveDTO.getId());
		if (!planContent.getStatus().equals(TaskStatusEnum.PARTS_CHANGE.getStatus())) {
			throw new ServiceException("任务状态已变更，请刷新重试！");
		}

		// 系统代签 任务提交时 未签退人员自动签退
		signService.checkUserSignOut(partsWorkSaveDTO.getId());

		// 统计人员上传图片总数
		List<MaintainPlanContentUser> planUsers = planContentUserService.list(Wrappers.<MaintainPlanContentUser>lambdaQuery().eq(MaintainPlanContentUser::getPlanId, partsWorkSaveDTO.getId()));
		planUsers.forEach(e -> {
			List<MaintainMalfunctionHistory> malfunctionHistories = malfunctionHistoryService.listByPlanUser(partsWorkSaveDTO.getId(), e.getUserId());
			int userImgNum = 0;
			if (ObjectUtil.isNotEmpty(malfunctionHistories)) {
				userImgNum = malfunctionHistories.stream().filter(j -> ObjectUtil.isNotEmpty(j.getDisposeImgUrl())).map(j -> j.getDisposeImgUrl().stream().filter(k -> "image".equals(k.get("type"))).count()).mapToInt(Long::intValue).sum();
			}
			e.setImageNum(userImgNum);
		});
		planContentUserService.updateBatchById(planUsers);

		// 更新工单状态
		planContent.setStatus(TaskStatusEnum.PARTS_FINISH.getStatus());
		planContentService.update(planContent);

		// 插入工单记录
		malfunctionLogService.insertWorkLog(partsWorkSaveDTO.getId(), TaskStatusEnum.getTaskName(planContent.getTypeStatus(), planContent.getStatus()), planContent.getStatus());

		// 飞书-修改配件状态-已完成
//		if (Func.equalsSafe("592800", AuthUtil.getTenantId())) {
//			FeiShuDocumentEnum documentEnum = null;
//			if (environment.acceptsProfiles("prod")) {
//				documentEnum = FeiShuDocumentEnum.PART_APPLY_RECORD;
//			} else {
//				documentEnum = FeiShuDocumentEnum.PART_APPLY_RECORD_COPY2;
//			}
//			UpdateBitableDataDTO bitableData = new UpdateBitableDataDTO();
//			bitableData.setAppToken(documentEnum.getAppToken());
//			bitableData.setTableId(documentEnum.getTableId());
//			bitableData.setPlanIdField("配件申请编号");
//			bitableData.setPlanId(planContent.getId());
//			Map<String, Object> value = new HashMap<>(2);
//			value.put("结果", TaskStatusEnum.PARTS_FINISH.getName() + "-操作成功");
//			bitableData.setValue(value);
//			asyncHttpUtil.createPost(projectApiConfiguration.getWeb() + "/admin/feishu/parts/updateBitableByPlanId", Func.toJson(bitableData), WebUtil.getRequest());
//		}
		return Boolean.TRUE;
	}

	@Override
	public PartsWorkDetailVO selectPartsWorkDetail(Long planId) {
		MaintainPlanContent planContent = planContentService.getById(planId);
		PartsWorkDetailVO partsWorkDetailVO = baseMapper.selectPartsWorkDetail(planId);
		if (ObjectUtil.isEmpty(planContent)) {
			throw new ServiceException("未找到对应配件工单");
		}
		List<MaintainPartsWork> partsList = baseMapper.selectListByPlan(planId);
		List<MaintainPartsWorkSku> skuList = partsWorkSkuService.selectListByWorkIds(partsList.stream().map(MaintainPartsWork::getId).collect(Collectors.toList()));
		partsList.forEach(e -> {
			e.setSkuList(skuList.stream().filter(t -> t.getWorkId().equals(e.getId())).collect(Collectors.toList()));
		});
		partsWorkDetailVO.setPartsList(partsList);
		// 2025-06 封装拓展信息用于展示新铭牌保存逻辑, 为了尽可能避免getOne产生的问题，使用list查询，一般情况下仅有一条
		List<MaintainPlanContentExt> extMessageList = planContentExtService.list(
			Wrappers.<MaintainPlanContentExt>lambdaQuery()
				.eq(MaintainPlanContentExt::getPlanId, planId)
				.eq(BaseEntity::getIsDeleted, 0)
		);
		if(Func.isNotEmpty(extMessageList)){
			partsWorkDetailVO.setMaintainPlanContentExt(extMessageList.get(0));
		}
		if (Func.isNotEmpty(partsWorkDetailVO.getMalDetailVO()) && Func.isNotEmpty(partsWorkDetailVO.getMalDetailVO().getFaultMessageList())) {
			partsWorkDetailVO.getMalDetailVO().getFaultMessageList().forEach(e -> {
				if (ObjectUtil.isNotEmpty(e.getProblemItem())) {
					String problemItem = String.valueOf(e.getProblemItem());
					List<String> problemNames = new ArrayList<>();
					List<String> problemItemKey = Func.toStrList(problemItem);
					for (String key : problemItemKey) {
						String problemName = DictCache.getValue("fault_problem", key);
						problemNames.add(problemName);
					}
					e.setProblemItemNames(problemNames);
				}
			});
		}
		partsWorkDetailVO.setDetailTitle(partsWorkDetailVO.getCreateUserName() + "的配件申请");

		// 查询该任务电梯最近一次完成的任务
		LastPlanVO lastPlanVO = planContentService.selectElevatorLastPlan(partsWorkDetailVO.getElevatorId(), planId);
		partsWorkDetailVO.setLastPlanVO(lastPlanVO);

		// 查询维修操作记录
		List<MalFunctionHistoryVO> malFunctionHistories = malfunctionHistoryService.selectByPlanId(planId);
		partsWorkDetailVO.setMalFunctionHistories(malFunctionHistories);

		// 查询关联人员信息
		List<MaintainPlanContentUser> planContentUsers = planContentUserService.list(Wrappers.<MaintainPlanContentUser>lambdaQuery().eq(MaintainPlanContentUser::getPlanId, planId));
		if (ObjectUtil.isNotEmpty(planContentUsers)) {
			planContentUsers = planContentUsers.stream().filter(e -> {
				String userName = userService.getById(e.getUserId()).getRealName();
				e.setUserName(userName);
				Integer userSignCount = signService.count(Wrappers.<MaintainSign>lambdaQuery().eq(MaintainSign::getPlanId, e.getPlanId()).eq(MaintainSign::getUserId, e.getUserId()));
				e.setUserSignCount(userSignCount);
				if (planContent.getStatus().equals(TaskStatusEnum.PARTS_FINISH.getStatus())) {
					int signCount = signService.count(Wrappers.<MaintainSign>lambdaQuery().eq(MaintainSign::getPlanId, planId).eq(MaintainSign::getUserId, e.getUserId()));
					if (signCount > 0) {
						return true;
					}
				} else {
					return true;
				}
				return false;
			}).collect(Collectors.toList());
			partsWorkDetailVO.setPlanContentUsers(planContentUsers);
		}

		partsWorkDetailVO.getPartsList().forEach(p -> {
			// 新增业务拆解文件后缀
			List<HashMap<String, String>> extWordUrl = p.getExtWordUrl();
			if (Func.isNotEmpty(extWordUrl)) {
				for (HashMap<String, String> e : extWordUrl) {
					String name = e.get("name");
					// 当这个key存在时，拆分后缀
					if (!Func.isNull(name)) {
						int index = name.lastIndexOf(".");
						String type = name.substring(index, name.length());
						e.put("type", type);
					}
				}
			}
			p.setExtWordUrl(extWordUrl);
		});

		// 配件收货地址
		PartAddress partAddress = partAddressService.getOne(Wrappers.<PartAddress>lambdaQuery().eq(PartAddress::getPlanId, planId), false);
		partsWorkDetailVO.setPartAddress(partAddress);

		// 流程审批节点flow
//		BladeFlow bladeFlow = new BladeFlow();
//		bladeFlow.setProcessInstanceId(planContent.getProcessInstanceId());
//		List<BladeFlow> flowList = flowBusinessService.selectTodoList(bladeFlow);
//		if (Func.isNotEmpty(flowList)) {
//			partsWorkDetailVO.setTaskFlow(flowList.get(0));
//		}
		Long elevatorId = planContent.getElevatorId();
		List<ElevatorAttachmentHistory> list = elevatorAttachmentHistoryService.list(Wrappers.<ElevatorAttachmentHistory>lambdaQuery().eq(ElevatorAttachmentHistory::getElevatorId, elevatorId).eq(ElevatorAttachmentHistory::getStatus, ElevatorAttachmentEnum.NAME.getStatus()).orderByDesc(ElevatorAttachmentHistory::getCreateTime));
		if (Func.isNotEmpty(list)) {
			partsWorkDetailVO.setElevatorAttachmentHistory(list.get(0));
		} else {
			partsWorkDetailVO.setElevatorAttachmentHistory(new ElevatorAttachmentHistory());
		}
		return partsWorkDetailVO;
	}

	@Override
	public IPage<ElevatorMalfunctionPartsVO> selectElevatorPartsWorkPage(PartsWorksPageQuery pageQuery, IPage<ElevatorMalfunctionPartsVO> page) {
		if (!Func.isNull(pageQuery.getAuditStatus())) {
			// 新增当前用户信息
			if (pageQuery.getAuditStatus() == 1 && Func.isNull(pageQuery.getDispose())) {
				Long userId = AuthUtil.getUserId();
				pageQuery.setUserId(userId);
			}
		}
		IPage<ElevatorMalfunctionPartsVO> partsPlanList = page.setRecords(baseMapper.selectPartsPlanListLow(pageQuery, page));
		if (ObjectUtil.isNotEmpty(partsPlanList.getRecords())) {
			partsPlanList.getRecords().forEach(e -> {
				// 封装故障描述
				if (ObjectUtil.isNotEmpty(e.getProblemItem())) {
					String problemItem = String.valueOf(e.getProblemItem());
					List<String> problemNames = new ArrayList<>();
					List<String> problemItemKey = Func.toStrList(problemItem);
					for (String key : problemItemKey) {
						String problemName = DictCache.getValue("fault_problem", key);
						problemNames.add(problemName);
					}
					e.setProblemItemNames(problemNames);
				}
				// 封装审批状态描述
				e.setAuditStatusName(TaskStatusEnum.getPartsAuditStatusName(e.getStatus()));
				// 封装审批节点描述
				List<BladeFlow> flowList = partsService.historyFlowList(e.getProcessInstanceId());
				if (ObjectUtil.isNotEmpty(flowList)) {
					e.setAuditNode(flowList.get(flowList.size() - 1).getHistoryActivityName());
				}
			});
		}
		return partsPlanList;
	}

	@Override
	public HashMap<String, Object> selectElevatorPartsWorkAuditPage(PartsWorksPageQuery pageQuery, IPage<ElevatorMalfunctionPartsVO> page) {

		HashMap<String, Object> resultMap = new HashMap<>();

		BladeFlow bladeFlow = new BladeFlow();
		bladeFlow.setProcessDefinitionKey(ProcessConstant.PARTS);
		bladeFlow.setTaskName(String.format("%s,%s", PartsApproveRoleEnum.GROUP.getTaskName(), PartsApproveRoleEnum.MANAGER.getTaskName()));

		// 获取本人未处理或已处理流程
		List<String> processInstanceIds = null;
		List<BladeFlow> flowList = null;
		List<BladeFlow> todoList = flowBusinessService.selectTodoList(bladeFlow);
		List<BladeFlow> doneList = flowBusinessService.selectDoneList(bladeFlow);
		if (pageQuery.getDispose().equals(1)) {
			flowList = todoList;
		} else {
			flowList = doneList;
		}
		if (ObjectUtil.isNotEmpty(flowList)) {
			processInstanceIds = flowList.stream().map(BladeFlow::getProcessInstanceId).collect(Collectors.toList());
			pageQuery.setProcessInstanceIds(processInstanceIds);
			IPage<ElevatorMalfunctionPartsVO> resultPage = selectElevatorPartsWorkPage(pageQuery, page);
			List<BladeFlow> finalFlowList = flowList;
			resultPage.getRecords().forEach(e -> {
				finalFlowList.forEach(j -> {
					if (e.getProcessInstanceId().equals(j.getProcessInstanceId())) {
						e.setTaskId(j.getTaskId());
					}
				});
			});
			resultMap.put("todoSize", todoList.size());
			resultMap.put("doneSize", doneList.size());
			resultMap.put("list", resultPage);
		} else {
			resultMap.put("todoSize", todoList.size());
			resultMap.put("doneSize", doneList.size());
			resultMap.put("list", page.setRecords(new ArrayList<>()));
		}
		return resultMap;
	}


	@Override
	public PartsSimpleInfoVO getPartsSimpleInfo(String processInstanceId) {
		return baseMapper.getPartsSimpleInfo(processInstanceId);
	}

	@Override
	public PartsSimpleInfoVO getPartsSimpleInfoByPlanId(Long planId) {
		return baseMapper.getPartsSimpleInfoByPlanId(planId);
	}

	@Override
	public List<MaintainPartsWork> getMaintainPartsWorkListOfMalId(List<Long> ids) {
		return baseMapper.getMaintainPartsWorkListOfMalId(ids);
	}

	@Override
	public IPage<PartsApplyDetailVO> partsApplyPage(Map<String, Object> param, IPage<PartsApplyDetailVO> page) {
		return page.setRecords(baseMapper.partsApplyPage(param, page));
	}

	@Override
	public boolean cancelApply(Long planId) {
		BusinessApprove businessApprove = businessApproveService.getByWorkOrderId(planId);
		if (businessApprove == null) {
			throw new ServiceException("未找到对应工单流程!");
		}
		ApproveBusinessFlow flowStrategy = ApproveBusinessStrategy.get(ApproveTypeEnum.ACCESSORY_APPLY.getId());
		return flowStrategy.cancel(businessApprove.getId());
	}

}























